package org.linuxsogood.boot.grpc.client;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import lombok.extern.slf4j.Slf4j;
import org.linuxsogood.boot.grpc.Greeting;
import org.linuxsogood.boot.grpc.HelloWorldServiceGrpc;
import org.linuxsogood.boot.grpc.Person;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @author liu.hongwei
 * @since 2020/11/10 17:49
 */
@Component
@Slf4j
public class HelloWorldClient {

    private HelloWorldServiceGrpc.HelloWorldServiceBlockingStub helloWorldServiceBlockingStub;

    @PostConstruct
    private void init() {
        final ManagedChannel managedChannel = ManagedChannelBuilder.forAddress("localhost", 6565).usePlaintext().build();

        helloWorldServiceBlockingStub = HelloWorldServiceGrpc.newBlockingStub(managedChannel);
    }

    public String sayHello(String firstName, String lastName) {
        final Person person = Person.newBuilder().setFirstName(firstName).setLastName(lastName).build();

        log.info("client sending{}", person);

        final Greeting greeting = helloWorldServiceBlockingStub.sayHello(person);

        log.info("client received {}", greeting);
        return greeting.getMessage();
    }


}
